<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手绘签名</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .set {
            width: 200px;
            height: 400px;
            border: 1px solid #ccc;
            position: absolute;
            right: 5px;
            top: 50%;
            padding: 20px;
        }

        button {
            margin-top: 50px;
            width: 100px;
            height: 50px;
            font-size: 18px;
            border-radius: 5px;
            background-color: #666;
            border: 1px solid #ccc;
            font-weight: bold;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="set">
        <h4>双击页面保存签名</h4>
        <button>重新签名</button>
    </div>
    <script>
        // 创建画布
        let canvas = document.createElement('canvas');
        // 设置画布大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        document.body.appendChild(canvas);
        const btn = document.querySelector('button');


        // 获取画布的上下文
        let conttext = canvas.getContext('2d');
        // 添加事件
        canvas.addEventListener('mousedown', function (e) {
            this.isMouseDown = true;
            // 移动画笔点击位置
            conttext.moveTo(e.pageX, e.pageY);
        })
        canvas.addEventListener('mousemove', function (e) {
            // 判断鼠标移动绘画
            if (this.isMouseDown) {
                // 当鼠标按下时才做绘画
                conttext.lineTo(e.pageX, e.pageY);
                conttext.stroke();
            }
        })
        // 将isMouseDown改为false状态
        canvas.addEventListener('mouseup', function (e) {
            this.isMouseDown = false;
        })

        // 双击保存签名事件
        canvas.addEventListener('dblclick', function () {
            let link = document.createElement('a');
            // 保存文件类型
            link.href = canvas.toDataURL('image/png');
            // 文件名称
            link.download = '手写签名';
            link.click();
        })

        // 刷新方法清空画布签名
        btn.addEventListener('click', function (e) {
            window.location = location;
        })
    </script>
</body>

</html>